package edu.pg.ipse.utils;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.jexl2.JexlContext;
import org.apache.commons.jexl2.JexlEngine;

/**
 * The <code>ExpressionParser</code> represents utility class that 
 * provide functionality for parsing and evaluating expressions, e.g. math expressions.
 * 
 * @author Alexey_Udalov
 */
public class ExpressionParser {

	private static ExpressionParser instance = new ExpressionParser();
	
	private static final JexlEngine jexlEngine = new JexlEngine();
	
	static {
		Map<String, Object> funcs = new HashMap<String, Object>();
        funcs.put("math", MathUtils.class);
		jexlEngine.setFunctions(funcs);
	}
	
	/**
	 * Constructor.
	 */
	private ExpressionParser() {}
	
	/**
	 * @return instance of class
	 */
	public static ExpressionParser getInstance() {
		return instance;
	}
	
	/**
	 * Evaluates a math expression
	 * 
	 * @param mathExpression math expression
	 * @param context context
	 * @return result
	 */
	public Object evaluate(String mathExpression, JexlContext context) {
		
		context.set("PI", Math.PI);
		
		return jexlEngine.createExpression(mathExpression).evaluate(context);
	}
	
}
